package com.main.usermanagement.domain.user.event.handler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.main.common.utils.exceptions.StackTraceLog;
import com.main.crossdomaineventmanagement.event.model.EventMessage;
import com.main.usermanagement.application.service.UserService;
import com.main.usermanagement.domain.user.event.payload.RegisterSuccessPayload;
import com.main.usermanagement.domain.user.event.payload.RollbackUserPayload;
import com.main.usermanagement.domain.user.repository.UserRepository;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.annotation.SelectorType;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;

@Service
@Slf4j
@RocketMQMessageListener(
        topic = "RollbackEventsTopic",
        consumerGroup = "RollbackConsumerGroup",
        selectorType = SelectorType.TAG,
        selectorExpression = "ROLLBACK_USER"
)
@Transactional
public class RollbackUserHandler implements RocketMQListener<MessageExt> {
    private final StackTraceLog stackTraceLog = new StackTraceLog();
    private final ObjectMapper objectMapper = new ObjectMapper()
            .registerModule(new JavaTimeModule());  // 仅注册 JavaTime 模块


    @Resource
    private UserService userService;
    public void handleRollbackEvent(String payload) {

        RollbackUserPayload rollbackUserPayload = null;
        try {
            // 反序列化 payload 为业务对象
            rollbackUserPayload = objectMapper.readValue(payload, RollbackUserPayload.class);
            log.info("收到用户回滚消息，原始内容: {}", rollbackUserPayload);
        } catch (JsonProcessingException e) {
            System.err.println("反序列化 payload 失败: " + e.getMessage());
        }
        assert rollbackUserPayload != null;
        Long userId = rollbackUserPayload.getUserId();
        Boolean result = userService.removeUserById(userId);
        if(result){
            log.info("用户 {} 因账户创建失败已回滚", userId);
        }else{
            log.info("用户 {} 回滚失败", userId);
        }
    }

    @Override
    public void onMessage(MessageExt msg) {
        try {
            EventMessage event = objectMapper.readValue(msg.getBody(), EventMessage.class);
            log.info("收到用户回滚消息，原始内容: {}", event.getPayload());
            handleRollbackEvent(event.getPayload());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}